<?php
    /**json返回工具类
     * Created by PhpStorm.
     * User: Administrator
     * Date: 2018\6\12 0012
     * Time: 14:57
     */
namespace app\common\utils;

class ExitJsonUtil extends BaseUtil
{
    static $_self = null;
    public static function getInstance(){
        if(empty(self::$_self)){
            self::$_self = new ExitJsonUtil();
        }
        return self::$_self;
    }

    /**返回列表数据
     * @param     $data
     * @param int $code
     */
    public function exitList($data,$code = 200,$other = ''){
        $result['code'] = $code;
        $result['data']['list'] = $data['list'];
        $result['data']['nowPage'] = $data['nowPage'];
        $result['data']['totalPage'] = $data['totalPage'];
        $result['other'] = $other;
        exit(json_encode($result));
    }

    /**返回普通数据
     * @param        $data
     * @param int    $code
     * @param string $other
     */
    public function exitData($data,$code = 200,$other = ''){
        $result['data'] = $data;
        $result['code'] = $code;
        $result['other'] = $other;
        exit(json_encode($result));
    }

    /** 中断并返回数据,后面程序继续执行,避免用户等待(immediate)  windows系统不可用
     *  windows没有效果
     *  可用于返回值后,继续执行程序,但程序占得所以自由没有释放,一致占用,务必注意,最好给单独脚本执行
     * @param $returnData
     * @return void
     */
    public function executeAfterReturning($returnData){
        $result['data'] = $returnData;
        $result['code'] = 200;
        $result['other'] = "";
        $returnData = json_encode($result);
        ob_end_clean();
        ob_start();
        echo $returnData;//返回结果给ajax
        $size = ob_get_length();// get the size of the output
        header("Content-Length: $size");// send headers to tell the browser to close the connection
        header('Connection: close');
        header("HTTP/1.1 200 OK");
        header("Content-Type: application/json;charset=utf-8");
        ob_end_flush();
        if(ob_get_length()) ob_flush();
        flush();
        if (function_exists("fastcgi_finish_request")) { // yii或yaf默认不会立即输出，加上此句即可（前提是用的fpm）
            fastcgi_finish_request(); // 响应完成, 立即返回到前端,关闭连接
        }
        ignore_user_abort(true);//在关闭连接后，继续运行php脚本
        set_time_limit(0); //no time limit，不设置超时时间（根据实际情况使用）
    }
}